<template>
  <div class="TotalMoney overflowY">
    <!--<div class="PageTitle"><i class="iconfont icon-jia"></i>费用结算</div>-->
    <div class="PageContent">

      <el-form :model="chargeData" :inline="true" ref="ruleForm" label-width="120px" class="demo-ruleForm"
               @submit.native.prevent>
        <div class="PageItem margintop20">
          <object id="LODOP_OB" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" width=0 height=0> 
            <embed id="LODOP_EM" type="application/x-print-lodop" width=0 height=0></embed>
          </object>
          <el-row :gutter="0" class="paddingleft2">
            <el-form-item label="零售编码:" prop="name">
              <el-input v-model="businessCode" ref="totalbusinessCode" @keyup.enter.native="searchData(businessCode)"
                        :maxlength="20">
                <el-button type="primary" slot="append" icon="el-icon-search"
                           @click="searchData(businessCode)"></el-button>
              </el-input>
            </el-form-item>
            <!--<el-button type="primary" style="margin-left:20px;" @click="searchData(businessCode)">扫描</el-button>-->
            <el-form-item label="逝者姓名:">
              <span class="titlecont" >{{chargeData.retailBusinessItem.deadName}}</span>
            </el-form-item>
            <el-form-item label="逝者业务编号:">
              <span class="titlecont" >{{chargeData.retailBusinessItem.businessCode}}</span>
            </el-form-item>
            <el-form-item label="付款人(付款单位):" label-width="180px">
              <span class="titlecont" >{{chargeData.retailBusinessItem.payerName}}</span>
            </el-form-item>
            <!-- <el-form-item label="家属姓名:">
              <span class="titlecont">{{chargeData.retailBusinessItem.memberName}}</span>
            </el-form-item> -->

          </el-row>
        </div>

        <el-row></el-row>
        <div class="PageItem marginbottom0">
          <el-row class="PageInfo">
            <i class="el-icon-location"></i>费用信息
          </el-row>
          <div class="border1">
            <el-table
              :data="chargeData.chargeItems"
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              stripe
              style="width: 100%;"
              @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                :selectable="selectable"
                width="50">
              </el-table-column>
              <el-table-column
                prop="itemName"
                align='center'
                label="服务、物品"
                width="200">
                <template slot-scope="{row,$index}">
                  <span>{{row.itemName}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                width="120">
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                width="100">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="总金额"
                width="100">
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                width="120">
              </el-table-column>
              <el-table-column
                prop="benefitCharge"
                align='right'
                label="减免"
                width="120">
              </el-table-column>
              <el-table-column
                prop="realityCharge"
                align='right'
                label="实收"
                width="120">
              </el-table-column>
              <el-table-column
                prop="asSettled"
                align='center'
                label="结算状态"
                width="120">
                <template slot-scope="{row,$index}">
                  <span v-if="row.asUnsettled==1" style="color: #f00;">不可结算</span>
                  <span v-else-if="row.asSettled==0">未结算</span>
                  <span v-else-if="row.asSettled==1">已结算</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="settleBatchNo"
                align='center'
                label="结算批次编号"
                min-width="200px">
              </el-table-column>
              <el-table-column
                prop="settleTime"
                align='center'
                label="结算时间"
                width="120">
              </el-table-column>
              <el-table-column
                prop="payType"
                align='center'
                label="付款方式"
                width="120">
              </el-table-column>
              <el-table-column
                prop="asVerify"
                align='center'
                label="操作"
                width="100">
                <template slot-scope="{row}">
                  <span v-if="row.asSettled==0 ||  row.realityCharge<=0  || row.asBusiness==1 || row.asRefund==1 "></span>
                  <span v-else-if="row.asSettled==1" @click="openRefund(row)">退费</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <hr style="margin-top:50px;">
          <div class="font16" style="text-align:right;">
            <div style="display: inline-block;height: 80px;line-height: 80px;vertical-align: bottom;">
              总费用合计:<span class="totalw">{{Charge.total}}</span>元
            </div>
            <div style="padding-left:30px;display: inline-block;">
              <div style="line-height: 40px;">
                已结算:<span class="totalw">{{ Charge.Settled }}</span>元，
                优惠:<span class="totalw">{{ Charge.discountCharge }}</span>元，
                减免:<span class="totalw">{{ Charge.benefitCharge }}</span>元，
                实收合计:<span class="totalw">{{ Charge.realityCharge }}</span>元
              </div>
              <div style="line-height: 40px;">
                未结算:<span class="totalw">{{ Charge.unSettled }}</span>元，
                优惠:<span class="totalw">{{ Charge.unDiscountCharge }}</span>元，
                减免:<span class="totalw">{{ Charge.unBenefitCharge }}</span>元，
                待付金额:<span class="totalw">{{ Charge.unrealityCharge }}</span>元
              </div>
            </div>
          </div>
          <el-row :gutter="30" style="text-align: right;margin:30px 0; ">
            <!-- <el-button type="primary"  plain  @click="loadChargeDetailWithId">打印收费明细</el-button> -->
            <el-button type="primary"  @click="NowPay">费用结算</el-button>
          </el-row>
        </div>
        <div class="PageItem ">
          <el-row class="PageInfo">
            <i class="el-icon-add-location"></i>结算历史记录
          </el-row>
          <div class="border1">
            <el-table
              :data="chargeData.chargeSettles"
              border
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              stripe
              style="width: 100%;"
              @selection-change="handleSelectionChangeHistory">
              <el-table-column
                type="selection"
                width="50">
              </el-table-column>
              <el-table-column align='center' prop="settleTime" label="结算时间" width="200">
              </el-table-column>
              <el-table-column
                prop="settleCharge"
                align='right'
                label="结算金额"
                width="100">
              </el-table-column>
              <el-table-column
                prop="settleType"
                align='center'
                label="结算方式"
                width="120">
              </el-table-column>
              <el-table-column
                prop="invoiceCode"
                align='center'
                label="发票代码"
                width="220">
              </el-table-column>
              <el-table-column
                prop="invoiceNo"
                align='center'
                label="发票号"
                width="200">
              </el-table-column>
              <el-table-column
                prop="receiptNo"
                align='center'
                label="收据号"
                min-width="200px">
              </el-table-column>
              <el-table-column
                prop="settleBatchNo"
                align='center'
                label="结算批次编号"
                width="200">
              </el-table-column>
              <el-table-column
                prop="settleUserName"
                align='center'
                label="经办人"
                width="100">
              </el-table-column>
              <el-table-column
                prop="payType"
                align='center'
                label="付款方式"
                width="120">
              </el-table-column>
              <el-table-column
                prop="asVerify"
                align='center'
                label="日结审核"
                width="100">
                <template slot-scope="{row}">
                  <span v-if="row.asVerify==0">未审核</span>
                  <span v-else-if="row.asVerify==1">已审核</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'>
                <template slot-scope="{row,$index}">
                  <div v-if="row.asVerify==0 && row.settleCharge>0 && row.asInvoice==0 && row.asRefund==0">
                    <el-button
                      size="small"
                      type="text"
                      @click.native.prevent="cancellation($index, row)">撤销结算
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-row :gutter="30" style="text-align: right;margin:30px 0; ">
            <el-button type="primary"  plain @click.native.prevent="loadChargeSettleDetailWithId">
              打印收费明细
            </el-button>
            <!-- <el-button type="primary" v-if="btnRight.btnTotalMoneyPrintInvoice" plain @click.native.prevent="printInvoice">
              打印发票
            </el-button>
            <el-button type="primary" v-if="btnRight.btnTotalMoneyPrintInvoice"   @click.native.prevent="InvoiceManager">
              发票管理
            </el-button> -->
          </el-row>
        </div>

      </el-form>
    </div>
    <el-dialog title="服务、物品详情"  :visible.sync="dialogFormVisible" center width="30%">
      <el-form :model="chargeitemwithid" ref="dialogForm" label-width="100px" class="demo-ruleForm"
               :disabled="chargeSaveFlag">
        <el-form-item label="名称">
          <el-input v-model="chargeitemwithid.itemName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="单价">
          <el-input type="number" v-model="chargeitemwithid.itemPrice" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input type="number" v-model="chargeitemwithid.itemNumber" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="chargeitemwithid.itemUnit" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="项目金额">
          <el-input type="number" v-model="chargeitemwithid.itemCharge" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="优惠金额">
          <el-input type="number" v-model="chargeitemwithid.discountCharge"
                    :disabled="chargeitemwithid.asSettled==0?false:true"></el-input>
        </el-form-item>
        <el-form-item label="减免金额">
          <el-input type="number" v-model="chargeitemwithid.benefitCharge"
                    :disabled="chargeitemwithid.asSettled==0?false:true"></el-input>
        </el-form-item>
        <el-form-item label="实际收费">
          <el-input type="number" v-model="chargeitemwithid.realityCharge" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="结算状态">
          <el-input v-if="chargeitemwithid.asSettled==0" v-model="chargeitemwithid.asSettled" :disabled="true">否
          </el-input>
          <el-input v-if="chargeitemwithid.asSettled==1" v-model="chargeitemwithid.asSettled" :disabled="true">是
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="savecharge">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="发票及收据修改"  :visible.sync="dialogchangeVisible" center width="30%">
      <el-form :model="changeinvoice" ref="dialogchange" label-width="100px" class="demo-ruleForm"
               :disabled="changeinvoicesaveFlag">
        <el-form-item label="结算时间">
          <el-input  v-model="changeinvoice.settleTime" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="结算金额">
          <el-input  v-model="changeinvoice.settleCharge" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="付款方式">
          <el-input v-model="changeinvoice.settleType" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="发票号">
          <el-input v-model="changeinvoice.invoiceNo" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="发票代码">
          <el-input v-model="changeinvoice.invoiceCode" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="收据号">
          <el-input  v-model="changeinvoice.receiptNo" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="发票抬头">
          <el-input v-model="changeinvoice.invoiceTitle" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="经办人">
          <el-input  v-model="changeinvoice.settleUserName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="changeinvoice.remark"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogchangeVisible = false">取 消</el-button>
        <el-button type="primary" @click="savechargesettlechangeinvoice(changeinvoice.id)">保存</el-button>
      </div>
    </el-dialog>
    <NowPayDialogS :NowPayFlag="NowPayFlag" :btnRight="btnRight" :businessCode="businessCode"
                  :multipleSelection="multipleSelection"
                  :totalCharge="totalCharge"></NowPayDialogS>
    <RefundDialogS :RefundDialogFlag="RefundDialogFlag" :businessCode="businessCode"
                  :RowSelection="refundSelection"
                  :totalCharge="totalCharge"  ></RefundDialogS>
    <InvoiceDialog :InvoiceDialogFlag="InvoiceDialogFlag" :businessCode="businessCode"
                  :totalCharge="totalCharge"></InvoiceDialog>
    <PrintInvoiceDialog  :PrintInvoiceFlag="PrintInvoiceFlag" :multipleSelectionHistory="multipleSelectionHistory" :businessCode="businessCode" ></PrintInvoiceDialog>

  </div>
</template>

<script>
    import * as Type from '@/api/service'
    import NowPayDialogS from '../dialog/NowPayDialogS'
    import RefundDialogS from '../dialog/RefundDialogS'
    import {toFixed} from "@/utils/tofixed"
    import {getLodop} from '@/utils/lodopFuncs'
    import {dataFormate} from '@/utils/index'
    import InvoiceDialog from '../dialog/InvoiceDialog'
    import PrintInvoiceDialog from '../dialog/PrintInvoiceDialog'

    export default {
        name: "RetailSettle",
        components: {
          PrintInvoiceDialog,
          InvoiceDialog,
          NowPayDialogS,RefundDialogS
        },
        data() {
            return {
              RefundDialogFlag:false,//退费对话框打开标志
              InvoiceDialogFlag:false,//发票管理对话框打开标志
              PrintInvoiceFlag:false,//打印发票
              refundSelection:{},//选中要退费的信息
                businessCode: "",
                moreFlag: false, //折叠
                chargeData: {
                    // "funeralDead": {
                    //     "id": 0,
                    //     "businessCode": "",
                    //     "deadName": "",
                    //     "certificateNo": "",
                    //     "deadGender": "",
                    //     "benefitDistrict": "",
                    //     "exemptionType": "",
                    //     "transportPlace": "",
                    //     "cremationNo": "",
                    //     "version": 0
                    // },
                    // "familyMember": {
                    //     "id": 0,
                    //     "memberName": "",
                    //     "certificateNo": "",
                    //     "memberRelation": "",
                    //     "mobilePhone": "",
                    //     "otherPhone": "",
                    //     "version": 0
                    // },

                    retailBusinessItem:{},

                    "chargeItems": [],
                    "chargeSettles": []
                },
                chargeitemwithid: {
                  "id": 0,
                  "businessCode": "string",
                  "serviceItemId": 0,
                  "itemName": "string",
                  "itemPrice": 0,
                  "itemNumber": 0,
                  "itemUnit": "string",
                  "itemCharge": 0,
                  "discountCharge": 0,//优惠金额
                  "benefitCharge": 0,//减免金额
                  "realityCharge": 0,
                  "chargeTime": "string",
                  "asSettled": 0,
                  "randomCode": "string",
                  "version": 0
                },
                chargeSaveFlag: false,     //保存过程中不可更改,true为正在保存
                changeinvoice: {
                    id: 0,
                    "settleTime": "",
                    "settleCharge": 0,
                    "settleType": "",
                    "invoiceCode": "",
                    "invoiceNo": "",
                    "receiptNo": "",
                    "settleBatchNo": "",
                    "settleUserName": "",
                    "asVerify": 0,
                    remark: "",
                    version: 0,
                },
                changeinvoicesaveFlag: false, //保存过程中不可更改,true为正在保存
                dialogFormVisible: false,
                dialogchangeVisible: false,
                dictionary: {},
                showEdit: [],          //显示编辑框
                NowPayFlag: false,             //直接付款
                multipleSelection: [],
                multipleSelectionHistory: [],//结算历史选择
                totalCharge: 0,//选择总费用
                btnRight: {//按钮权限
                    btnTotalMoneyCodeScanning: true,  //业务编码扫码按钮
                    btnBusinessCodeBoneAsh: true,//打印骨灰盒二维码
                    btnTotalMoneyPrintChargeItem: true,//打印收费明细
                    btnTotalMoneyExpenseSettlement: true, //费用结算
                    btnTotalMoneyPrintHistoryItem: true, //打印收费明细
                    btnTotalMoneyPrintInvoice: true, //打印发票
                    btnNowPaySave: true,  //费用结算保存
                    btnNowPayCancel: true,//费用结算取消
                },
            }

        },
        mounted() {
            //按钮权限
            this.btnRight = this.$route.meta.buttons;
            //遍历属性赋值将true与false字符串转换成布尔型的值
            for (let key of Object.keys(this.btnRight)) {
                this.btnRight[key] = (this.btnRight[key] || this.btnRight[key] == "true") ? true : false;
            }
            this.businessCode = this.$route.params.retailBusinessCode
            if (this.businessCode!=null && this.businessCode!="") {
                this.searchData(this.businessCode)
            }

            // //businessCode获得焦点
            // this.$refs["totalbusinessCode"].focus()
        },
        methods: {
          //打开退费窗口
          openRefund(row){
            let this_open=this;
            if(row && row.id){
              let postData = {
                "id": row.id
              }
              Type['loadchargeitemwithid'](postData).then(response => {
                const {data} = response;
                if (!data) {
                  this_open.$message('数据读取失败')
                  return
                }
                //判断是否已退费用   data.asRefund ||data.asRefund==1 ||data.total<=0 || data.refundId != null   退费用asRefund==1的不允许退费
                if( data.asRefund==1 ||data.total<=0 ){
                  this_open.$message('费用为负,为零,已退费记录,不允许退费用')
                }else{
                  this_open.refundSelection = data
                  //对话框显示
                  this_open.RefundDialogFlag=true;
                }
                //查询退费用详细,不是从row获得，而是查数据库得来的数据
               }).catch(error => {
                this_open.$message(error)
              })
             }
          },
            //数据读取
            ReadData() {
                if (!this.businessCode || this.businessCode.length == 0) {
                  this.$message("请输入业务编码");
                  return
                }
                let postData = {
                    "businessCode": this.businessCode
                }
                Type['loadRetailChargeSettlementAll'](postData).then(response => {
                    const {data} = response;
                    if (!data) {
                        this.$message('数据读取失败')
                        return
                    }

                    this.chargeData = data;

                }).catch(error => {
                    this.$message(error)
                })
            },//去掉左右空格
            trim(str) {
                if (str == null) {
                    return "";
                }
                return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1');
            },//查询业务编码
            searchData() {
                if (!this.businessCode || this.businessCode.length == 0) {
                    this.$message("请输入业务编码");
                    return
                }
                //去掉左右空格
                this.businessCode = this.trim(this.businessCode);
                // this.$store.dispatch('user/setbusinessCode', this.businessCode).catch(()=>console.log('promise catch err'));
                this.ReadData();
            },
            editTable(index, row) {
                let postData = {
                    "id": row.id
                }
                Type['loadchargeitemwithid'](postData).then(response => {
                    const {data} = response;
                    if (!data) {
                        this.$message('数据读取失败')
                        return
                    }
                    this.chargeitemwithid = data;
                    this.chargeitemwithid.asSettled = row.asSettled
                    // this.dialogFormVisible = true;
                }).catch(error => {
                    this.$message(error)
                })
                this.dialogFormVisible = true;    //测试用
            },
            savecharge() {
                this.chargeSaveFlag = true;
                let postData = this.chargeitemwithid

                Type['savechargeitemwithid'](postData).then(response => {
                    const {data} = response;
                    if (!data) {
                        this.$message('保存读取失败')
                        return
                    }
                    this.chargeitemwithid = data;
                    this.ReadData()
                }).catch(error => {
                    this.$message(error)
                })
                this.chargeSaveFlag = false;
            },
            //设置是否选中
            selectable(row, index) {
                if (row.asSettled == 1 || row.asUnsettled == 1) {
                    return false
                } else {
                    return true
                }
            },
            handleSelectionChange(val) {
              console.log(val,333)
                let itemArray = [];
                let totalLocal = 0;
                val.forEach(item => {
                    //未结算的
                    if (item.asSettled == 0) {
                        //计算总金额
                        totalLocal += Number(item.itemPrice);
                        itemArray.push(item);

                    }
                })

                this.multipleSelection = itemArray;
                this.totalCharge = totalLocal;
                console.log(this.multipleSelection,this.totalCharge,888888888)
            },
            handleSelectionChangeHistory(val) {
                this.multipleSelectionHistory = val;
            },
            //点击编辑,作废，发票管理已处理，不需要再用修改来操作发票号

            savechargesettlechangeinvoice(id) {
                this.changeinvoicesaveFlag = true
                let postData =
                    {
                        "id": id,
                        "businessCode": this.businessCode,
                        "invoiceCode": this.changeinvoice.invoiceCode,
                        "invoiceNo": this.changeinvoice.invoiceNo,
                        "invoiceTitle": this.changeinvoice.invoiceTitle,
                        "remark": this.changeinvoice.remark,
                        "version": this.changeinvoice.version
                    }
                Type['savechargesettlechangeinvoice'](postData).then(response => {
                    this.$message("保存成功")
                    this.ReadData()
                }).catch(error => {
                    this.$message(error)
                })
                this.changeinvoicesaveFlag = false
                this.dialogchangeVisible = false;
            },
            //撤销结算
            cancellation(index, row) {
               //确认是否撤销结算
              this.$confirm('确认是否撤销结算, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                //点击确定的操作(撤销结算)
                let ids = []
                ids.push({id: row.id, version: row.version})
                let postData = {
                  businessCode: this.businessCode,
                  ids: ids
                }
                Type['saveRetailChargeSettleToCancellationSettlement'](postData).then(response => {
                  if (response){
                    this.$message("执行成功")
                  }
                  this.ReadData()
                }).catch(error => {
                  this.$message(error)
                })
              }).catch(() => {

              });

            }, //载入收费明细信息
          loadChargeDetailWithId(){
           let  this_print=this;
           let  chargeItems=this.multipleSelection;
           let  item=null;
           let  chargeArray=[];
           if(chargeItems && chargeItems.length>0){
              for(let i=0;i<chargeItems.length;i++){
                item=chargeItems[i];
                chargeArray.push({
                  "id":item.id,
                  "version":item.version
                });
              }
           }
            let postData = {
              "businessCode": this_print.businessCode,
              "ids":chargeArray
            }

            Type['loadPrintRetailChargeDetailsWithId'](postData).then(response => {
              //接收返回数据
              let result = response.data;
              //调用打印接口
              this_print.printChargeSettleDetailWithId(result);
            }).catch(error => {
              this_print.$message(error)
            })
          },
          //载入收费明细信息
          //打印未结算清单明细
          printChargeDetailWithId(printData){

            let LODOP =  getLodop();
            if (LODOP == null || !LODOP) {
              this.$.messager.alert('系统提示', '您的浏览器不支持打印控件，请用IE重试或安装打印控件后重试');
              return;
            }
            //当前业务时间
            let  businessTime=dataFormate(new Date());
            //业务编码
            let  firstParty="临沂市第二殡仪馆";
            //标题
            let  title="<b>"+firstParty+"费用明细单</b>";
            //业务编号
            let  businessCode=printData.retailBusinessCode;
            //逝者姓名
            let  deadName=""+printData.payerName;
            //付款方式
            let  settleType=printData.settleType==null?"":printData.settleType;
            //收费日期
            let  settleTime=printData.chargeDate;
            let  chargeItems=printData.chargeItems;
            let  tableHead="<table border='1' style='border-collapse: collapse'><tr><td>付款人：</td><td>"+deadName+"</td><td>收费日期</td><td>"+settleTime+"</td></tr>";
            let  chargeItemStr="<tr>";
            if( chargeItems && chargeItems.length>0){
                 let item=null;
                 for(let k=0;k<chargeItems.length;k++){
                        item=chargeItems[k];
                        chargeItemStr+="<td>"+item.itemName+"</td><td>"+item.itemCharge+"</td>";
                        if(k!=0 && k%3==0 && k!=chargeItems.length-1){
                          chargeItemStr+="</tr><tr>";
                        }
                 }
                         chargeItemStr+="</tr>";
            }
            //制单日期
            let  printTime="制单日期："+printData.printDate;
            //应收
            let  yingShou="应收："+printData.itemTotalCharge;
            //零售无费用减免
            //费用减免
            let  chargeJianMian="费用减免："+printData.discountTotalCharge==null?0:printData.discountTotalCharge;
            //实收
            let  activeCharge="实收："+printData.realityTotalCharge;
            //大写
            let  txtDaXie="大写："+printData.realityTotalChargeText;
            //制单人
            let   markMan=printData.userFullName;
            let tableBottom="<tr><td colspan='8'>"+yingShou+chargeJianMian+activeCharge+txtDaXie+"</td></tr></table>";
            let table=tableHead+chargeItemStr+tableBottom
            //生前住址
            //纸张
             LODOP.SET_PRINT_PAGESIZE(1, 0, 0, "A4");
            //设置字体
            LODOP.SET_PRINT_STYLE("FontSize",11);
            //调用打印控件进行测试
            LODOP.ADD_PRINT_HTM(50,280,300,25,title);
            LODOP.ADD_PRINT_TEXT(90,450,300,25,"业务编号："+businessCode);
            //打印协议
            LODOP.ADD_PRINT_HTM(120,50,650,125,table);
            //制单日期
            LODOP.ADD_PRINT_TEXT(300,50,300,25,printTime);
            //制单人
            LODOP.ADD_PRINT_TEXT(300,400,500,25,markMan);
            //打印预览
            LODOP.PREVIEW();
            //直接打印
            //LODOP.PRINT();
            //LODOP.PRINT_DESIGN();
          },

      //载入已结算费用清单
           loadChargeSettleDetailWithId(){
              //选中历史
             let  chargeItems=this.multipleSelectionHistory;
             let  item=null;
             let  chargeArray=[];
             if(chargeItems && chargeItems.length>0){
               for(let i=0;i<chargeItems.length;i++){
                 item=chargeItems[i];
                 chargeArray.push({
                   "id":item.id,
                   "version":item.version
                 });
               }
             }
             let postData = {
               "businessCode": this.businessCode,
               "ids":chargeArray
             }
            Type['loadPrintRetailChargeSettleDetailsWithId'](postData).then(response => {
              //接收返回数据
              let result = response.data;
              //调用打印接口
              this.printChargeSettleDetailWithId(result);
            }).catch(error => {
              this.$message(error)
            })
          }, //打印结算清单明细
          printChargeSettleDetailWithId(printData){
            let this_print=this;
            let LODOP =  getLodop();
            if (LODOP == null || !LODOP) {
              this_print.$.messager.alert('系统提示', '您的浏览器不支持打印控件，请用IE重试或安装打印控件后重试');
              return;
            }
            //二维码
            let recCode=printData.retailBusinessCode;
            console.log(recCode);
            //减免类型
            let jianMianType="减免类型："+"减免类型";
            //业务编码
            let businessCode=printData.businessCode;
            //付款方式
            let selltedType=printData.payType;
            //收费日期
            let  businessTime=printData.chargeDate;
            //业务编码
            let  title="临沂市第二殡仪馆 费用明细单";
            //逝者姓名
            let  deadName=printData.deadName;
            let payerName=printData.payerName
            let  chargeItems=printData.chargeItems;
            let chargeItemStr = "<tr style='border-style: none'><td>服务项目</td><td>应收</td><td>服务项目</td><td>应收</td><td>服务项目</td><td>应收</td><td>服务项目</td><td>应收</td></tr><tr style='border-style: none'>";
            if (chargeItems && chargeItems.length > 0) {
              let item = null;
              for (let k = 0; k < chargeItems.length; k++) {
                item = chargeItems[k];
                chargeItemStr +=
                  "<td>" + item.itemName + "</td><td>" + item.itemCharge + "</td>";
                if (k != 0 && (k+1) % 4 == 0&&k!=chargeItems.length-1) {
                  chargeItemStr += "</tr><tr>";
                }
                if (k==chargeItems.length-1&&(k+1)%4!=0){
                  for(let kk=0;kk<(4-(k+1)%4);kk++){
                    chargeItemStr+="<td>&nbsp;</td><td>&nbsp;</td>";

                  }
                }
              }
              chargeItemStr += "</tr>";
            }
            let discountChargeItems=printData.discountChargeItems;
            let jianMainStr="<tr>";
            if(discountChargeItems && discountChargeItems.length>0){
              let jianMainItem=null;
              for (let j = 0; j < discountChargeItems.length; j++) {
                jianMainItem = discountChargeItems[j];
                jianMainStr += jianMainItem.itemName + jianMainItem.itemPrice;
              }
            }
            jianMainStr += "</tr>";
            //制单日期
            let printTime = "制单日期：" + printData.printDate;
            //应收
            let yingShou = "应收：" + printData.itemTotalCharge;
            //零售无费用减免
            /* //费用减免
             let chargeJianMian = "0";
             if(printData.discountTotalCharge!=null&&printData.discountTotalCharge.trim().length!=0) {
               chargeJianMian=printData.discountTotalCharge;
             }
             chargeJianMian = "费用减免：" + chargeJianMian;*/
            //实收
            let activeCharge = "实收：" + printData.realityTotalCharge;
            //大写
            let realityTotalChargeText = "大写：" + printData.realityTotalChargeText;
            //制单人
            let markMan = "制单人：" + printData.userFullName;
            let beforeDeathAddress = printData.beforeDeathAddress
            //let tableBottom="<tr><td colspan='7'>"+yingShou+chargeJianMian+activeCharge+realityTotalChargeText+"</td></tr></table>";
            let dataTable = "<table>" +
              "<tr>" +
              "<td width='200px'>付款人：" + payerName + "</td>" +
              "<td width='200px'>付款方式：" + selltedType + "</td>" +
              "<td width='200px'>收费日期：" + businessTime + "</td>" +
              "</tr>"+
              //"<tr><td colspan='2'>生前住址：" + beforeDeathAddress + "</td></tr>" +
              "</table>";
            dataTable+= "<table align='center' cellpadding='0' cellspacing='0' width='99%' border='1' style='text-align: center ;border-collapse: collapse;'>" +
              chargeItemStr +
              "<tr><td colspan='8'>" + yingShou + "&nbsp;&nbsp;" + activeCharge + "&nbsp;&nbsp;" + realityTotalChargeText + "</td></tr>" +
              "</table>";
            dataTable+="<table><tr><td width='450px'>"+printTime+"</td><td>"+markMan+"</td></tr></table>";
            LODOP.SET_PRINT_STYLE("FontSize",11);
            //调用打印控件进行测试
            LODOP.ADD_PRINT_BARCODE("4mm", "160mm", "28mm", "28mm", "QRCode", recCode);
            LODOP.ADD_PRINT_HTM(20, 260, 300, 25, "<p style='font-size:20px;font-weight: bold;'>" + title + "</p>");
            //LODOP.ADD_PRINT_TEXT(90,50,350,25,jianMianType);
            LODOP.ADD_PRINT_TEXT(50, "15mm", 500, 25, "业务编号：" + recCode);
            //打印协议
            LODOP.ADD_PRINT_HTM(120,50,650,125,dataTable);
            // LODOP.ADD_PRINT_HTM(260,50,350,25,printTime);
            // LODOP.ADD_PRINT_HTM(260,400,650,25,markMan);
            //打印预览
            LODOP.PREVIEW();

          },
          printItems() {
                this.$message('打印明细');
                if (this.multipleSelection.length == 0) {
                    this.$message("请选择服务项目")
                    return
                }
            }, //打印发票
              printInvoice() {
                let printFlag=this.checkPrintInvoice();
                if(! printFlag){
                  this.$message("请选择未打印过发票或未退费的结算记录打印，打印过的请进发票管理重打！")
                }else{
                  this.PrintInvoiceFlag=true
                }
            },//检查打印发票的选择项
             checkPrintInvoice(){
               let flag=true;
               //采用后台验证,后面接口完成后改成后台验证方式
               let selectData=this.multipleSelectionHistory
               let  totalCharge=0;
               if(selectData && selectData.length>0){
                 let item=null;
                 for(let i=0;i<selectData.length;i++){
                     item=selectData[i];
                    let  settleCharge = new Number(item.settleCharge)
                         totalCharge += settleCharge
                   //item.asRefund==1只是记录不能退费，不能记录不能打印发票
                     if(item.invoiceNo|| item.invoiceCode){
                         flag=false
                       break;
                     }
                 }
               }
               if(totalCharge<=0){
                  flag=false
                  return flag;
               }
               return flag;
            },
              //发票管理
              InvoiceManager() {
                this.InvoiceDialogFlag=true
            },
            //退费
            Refund(index) {
                let ids = []
                this.multipleSelectionHistory.forEach(n => {
                    if (n.id) {
                        ids.push(n.id)
                    }
                })
                let postData = {
                    businessCode: this.businessCode,
                    ids: ids
                }
                Type['savechargesettletorefund'](postData).then(response => {
                    this.$message(response.msg)
                    this.chargeData = data;
                }).catch(error => {
                    this.$message(error)
                })

            },
            //直接付款
            NowPay() {
                if (this.multipleSelection.length == 0) {
                    this.$message("请选择服务项目")
                    return
                }
                this.NowPayFlag = true;
            },//表头样式
            tableHeadClass({row, rowIndex}) {
                // console.log(rowIndex) //表头行标号为0
                return {color: '#333', fontSize: '14px', fontWeight: 900, background: '#eee'}
            }
        },
        computed: {
            Charge() {
                let charge = {
                    total: 0.00,
                    Settled: 0.00,
                    discountCharge: 0.00,
                    benefitCharge: 0.00,
                    realityCharge: 0.00,
                    unSettled: 0.00,
                    unDiscountCharge: 0.00,
                    unBenefitCharge: 0.00,
                    unrealityCharge: 0.00
                }
                // console.log(this.chargeData.chargeItems,67876222222)
                this.chargeData.chargeItems.forEach(n => {

                    if (n.asSettled == 1) {  //已结算

                        if (n.itemCharge) {
                            charge.Settled += Number(n.itemCharge);
                        }
                        if (n.discountCharge) {
                            charge.discountCharge += Number(n.discountCharge);
                        }
                        if (n.benefitCharge) {
                            charge.benefitCharge += Number(n.benefitCharge);
                        }

                    } else if (n.asSettled == 0) {  //未结算

                        if (n.itemCharge) {

                            charge.unSettled += Number(n.itemCharge);
                        }
                        if (n.discountCharge) {


                            charge.unDiscountCharge += Number(n.discountCharge);
                        }
                        if (n.benefitCharge) {


                            charge.unBenefitCharge += Number(n.benefitCharge);
                        }

                    }

                })
                /*总费用合计*/
                charge.total = Number(charge.unSettled) + Number(charge.Settled)
                /*未结算*/
                charge.unrealityCharge = Number(charge.unSettled) - Number(charge.unDiscountCharge) - Number(charge.unBenefitCharge)
                /*已结算*/
                charge.realityCharge = Number(charge.Settled) - Number(charge.discountCharge) - Number(charge.benefitCharge)
                for (let i in charge) {
                    charge[i] = toFixed(charge[i], 2)
                }
                console.log(charge,6666666)
                return charge
            }
        },
        watch: {
            'NowPayFlag'() {
                if (this.NowPayFlag == false) {
                    this.ReadData()
                }
            },
          'PrintInvoiceFlag'() {
            if (this.PrintInvoiceFlag == false) {
              this.ReadData()
            }
          },
          'RefundDialogFlag'(){
            if (this.RefundDialogFlag == false) {
              this.ReadData()
            }
          },

        }
    }
</script>
<style>
  .TotalMoney .el-dialog__header {
    background-color: cornflowerblue !important;
    color: #fff;
  }

  .TotalMoney .PageContent .el-select .el-input, .TotalMoney .PageContent .el-select {
    width: 10vw;
    min-width: 120px;
  }
</style>
<style scoped>
  .el-form-item {
    margin-bottom: 5px !important;
  }

  .border1 {
    border: 1px solid #e2dada;
    padding: 10px;
  }

  .marginright50 {
    margin-right: 50px;
  }

  .edit-cell {
    padding: 3px;
  }

  .totalw {
    display: inline-block;
    width: 80px;
    font-weight: 600;
  }


</style>
